<?php 
$orderIds = $this->getRequest()->getPost('order_ids');
$_coreHelper = $this->helper('core');
$province_id = $this->getRequest()->getParam('province_id')?$this->getRequest()->getParam('province_id'):533;
$city_id = $this->getRequest()->getParam('city_id')?$this->getRequest()->getParam('city_id'):160;
$website_id = $this->getRequest()->getParam('website_id');
$category_id = $this->getRequest()->getParam('category_id');

$session = Mage::getSingleton('admin/session');
$roleId = $session->getUser()->getRoleId();
$roles = Mage::helper('zgb')->getUserRoles();
$zgb = Mage::helper('zgb');
$ids = array(0);
$storeIds = array(0);

$resource = Mage::getSingleton('core/resource');
$db = $resource->getConnection('core_read');

if($zgb->getRoleId('manufacturer') == $roleId)
{
	$manufacturer = Mage::getModel('zgb/manufacturer')->loadByAdminId($session->getUser()->getId());
	$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToFilter('manufacturer_id', array('eq'=>$manufacturer->getId()));
	foreach($products as $product)
	{
		if(!in_array($product->getId(),$ids))
		{
			$ids[] = $product->getId();
		}
	}
}else if($zgb->getRoleId('dealer') == $roleId){
	$dealer = Mage::getModel('zgb/dealer')->loadByAdminId($session->getUser()->getId());
	$sql = "SELECT distinct(entity_id) FROM `catalog_product_entity_int` WHERE attribute_id=138 AND `value`={$dealer->getId()}";
	$query = $db->query($sql);
	$products = $query->fetchAll();

	foreach($products as $product)
	{
		if(!in_array($product['entity_id'],$ids))
		{
			$ids[] = $product['entity_id'];
		}
	}

	$sql = "SELECT distinct(store_id) FROM `catalog_product_entity_int` WHERE attribute_id=138 AND `value`={$dealer->getId()}";
	$query = $db->query($sql);
	$stores = $query->fetchAll();

	foreach($stores as $store)
	{
		if(!in_array($store['store_id'],$storeIds))
		{
			$storeIds[] = $store['store_id'];
		}
	}
}

if($category_id)
{
	$sql = "SELECT item_id,stock.product_id,qty,website_id FROM `aitoc_cataloginventory_stock_item` as stock left join `catalog_category_product` cp on stock.product_id=cp.product_id where category_id='{$category_id}'";
}
else
{
	$sql = "SELECT item_id,product_id,qty,website_id FROM `aitoc_cataloginventory_stock_item` as stock where 1=1";
}

if($zgb->getRoleId('dealer') == $roleId)
{
	$websiteIds = array();
	foreach($storeIds as $sid)
	{
		if($sid==0) continue;
		$websiteIds[] = Mage::getModel('core/store')->load($sid)->getWebsite()->getId();
	}
	if($website_id)
	{
		if(in_array($website_id, $websiteIds))
		{
			$sql .= " and stock.website_id='{$website_id}'";
		}
		else
		{
			$sql .= " and stock.website_id='0'";
		}
	}
	else
	{
		if($city_id)
		{
			$websiteIds = array();
			foreach($storeIds as $sid)
			{
				if($sid==0) continue;
				$websiteIds[] = Mage::getModel('core/store')->load($sid)->getWebsite()->getId();
			}

			$websites = Mage::getModel('core/website')->getCollection()->addFieldToFilter('city_id', array('eq'=>intval($city_id)));
			$cityWebsiteIds = array();
			foreach($websites as $website)
			{
				$cityWebsiteIds[] = $website->getId();
			}
			foreach($cityWebsiteIds as $key=>$csid)
			{
				if(!in_array($csid, $websiteIds)) unset($cityWebsiteIds[$key]); 
			}
			if(empty($cityWebsiteIds)) $cityWebsiteIds[] = 0;
			$sql .= " and stock.website_id in (".implode(',', $cityWebsiteIds).")";
		}
		else
		{
			$sql .= " and stock.website_id in (".implode(',', $websiteIds).")";
		}
		
	}
}
else
{
	if($website_id)
	{
		$sql .= " and stock.website_id='{$website_id}'";
	}

	if(!$website_id && $city_id)
	{
		$websites = Mage::getModel('core/website')->getCollection()->addFieldToFilter('city_id', array('eq'=>intval($city_id)));
		$storeIds = array();
		foreach($websites as $website)
		{
			$storeIds[] = $website->getId();
		}
		if(empty($storeIds)) $storeIds[] = 0;
		$sql .= " and stock.website_id in (".implode(',', $storeIds).")";
	}
}

if($ids && $roleId != 1)
{
	$sql .= " and stock.product_id in (".implode(',',$ids).")";
}

$items = array();
$query = $db->query($sql);
$items = $query->fetchAll();

if($zgb->getRoleId('manufacturer')==$roleId && !$ids) $items = array();
?>
<div class="print">
	<div class="report-header">
		<h2>商品库存统计表</h2>
		<div class="search-box">
			<form name="report_form" id="report_form" action="" method="get">
				区域：
					<?php
                        $provinces = array();
                        $collection = Mage::getModel('directory/region')->getCollection()->addFieldToFilter('country_id', array('eq'=>'CN'));
                        $provinces[] = array('value'=>'','label'=>'-请选择-');
                        foreach($collection as $region)
                        {
                            $provinces[] = array('value'=>$region->getId(),'label'=>$region->getName());
                        }
                    ?>
					<select id="r_province_id" name="province_id">
						<?php foreach($provinces as $prov):?>
							<option value="<?php echo $prov['value'];?>" <?php if($prov['value']==$province_id) echo 'selected';?>><?php echo $prov['label'];?></option>
						<?php endforeach;?>
					</select>
					<?php
					$citys = array();
		            $citys[] = array('value'=>'','label'=>'-请选择-');
		            if($province_id)
		            {
			            $collection = Mage::getModel('chinaarea/city')->getCollection()->addFieldToFilter('region_id',array('eq'=>$province_id));
				        foreach($collection as $city)
				        {
				            $citys[] = array('value'=>$city->getId(), 'label'=>$city->getDefaultName());
				        }
			    	}
					?>
					<select id="r_city_id" name="city_id">
						<?php foreach($citys as $city):?>
							<option value="<?php echo $city['value'];?>" <?php if($city['value']==$city_id) echo 'selected';?>><?php echo $city['label'];?></option>
						<?php endforeach;?>
					</select>
					<?php
					$areas[] = array('value'=>'','label'=>'-请选择-');
					if($city_id){
				        $resource = Mage::getSingleton('core/resource');
				        $db = $resource->getConnection('core_read');
				        $sql = "select `area`.*,website.website_id from directory_country_area `area` right join core_website website on `area`.area_id=website.area_id where `area`.city_id='{$city_id}'";
				        $query = $db->query($sql);
				        $collection = $query->fetchAll();
				        
				        foreach($collection as $area)
				        {
				            $areas[] = array('value'=>$area['website_id'], 'label'=>$area['default_name']);
				        }
			    	}
					?>

					<select id="r_website_id" name="website_id">
						<?php foreach($areas as $area):?>
							<option value="<?php echo $area['value'];?>" <?php if($area['value']==$website_id) echo 'selected';?>><?php echo $area['label'];?></option>
						<?php endforeach;?>
					</select></br>
					<?php 
						$category = Mage::getModel("catalog/category")->load(12); 
						$categorys = $category->getChildrenCategories();
					?>

					<select id="category_id" name="category_id">
						<option value="">-请选择-</option>
						<?php foreach($categorys as $cate):?>
							<option value="<?php echo $cate->getId();?>" <?php if($cate->getId()==$category_id) echo 'selected';?>><?php echo $cate->getName();?></option>
						<?php endforeach;?>
					</select>
					<input type="submit" value="统计"/>
			</form>
		</div>
	</div>
	<script type="text/javascript">
		laydate({
		    elem: '#start_date', 
		    event: 'focus'
		});
		laydate({
		    elem: '#end_date', 
		    event: 'focus'
		});
	</script>
	<div class="order-print">
		<table class="data-table">
			<tr>
				<td>商品名称</td>
				<!-- <td width="8%">省份</td>
				<td width="8%">市</td> -->
				<td width="8%">区县</td>
				<td width="8%">单位</td>
				<td width="8%">库存数量</td>
			</tr>
			<?php foreach($items as $item):?>
			<?php
				$website = Mage::getModel('core/website')->load($item['website_id']);
				//echo $website->getCode();
				if($website->getCode()=='admin') continue;
				if($website->getCode()=='base') continue;
				$product = Mage::getModel('catalog/product')->load($item['product_id']);
			?>
			<tr>
				<td><?php echo $product->getName(); ?></td>
				<!-- <td><?php  ?></td>
				<td><?php  ?></td> -->
				<td><?php echo $website->getName() ?></td>
				<td><?php echo $product->getAttributeText('unit'); ?></td>
				<td><?php echo intval($item['qty']); ?></td>
			</tr>
			<?php endforeach;?>
		</table>
	</div>
</div>
<script type="text/javascript">
(function($){
	// $("#apply").click(function(){
	// 	if($("#r_province_id").val())
	// 	{
	// 		if(!$("#r_city_id").val())
	// 		{
	// 			alert("请选择城市");
	// 			return;
	// 		}
	// 	}
	// 	$("#report_form").submit();
	// });
	// if($('#r_province_id').val()=='') 
 //    {
 //        $('#r_city_id').attr('disabled',true);
 //        $('#r_website_id').attr('disabled',true);
 //    }
	$('#r_province_id').change(function(){      
        $.getJSON('<?php echo $this->getUrl('zgb/ajax/citys')?>?id='+$(this).val(), function(data){
            $('#r_city_id').empty();
            $('#r_website_id').empty();
            var option = $('<option>').val('').text('-请选择-');
            $('#r_website_id').append(option);
            for(var i=0; i<data.length;i++)
            {
                var option = $('<option>').val(data[i].value).text(data[i].label);
                $('#r_city_id').append(option);
            }
            $('#r_city_id').attr('disabled',false);
            $('#r_website_id').attr('disabled',true);
            $('#r_city_id').find('option:first').attr('selected',true);
        });
    });

    $("#r_city_id").change(function(){
        $('#r_website_id').attr('disabled',true);
        $.getJSON('<?php echo $this->getUrl('zgb/ajax/websites')?>?id='+$(this).val(), function(data){
            $('#r_website_id').empty();
            for(var i=0; i<data.length;i++)
            {
                var option = $('<option>').val(data[i].value).text(data[i].label);
                $('#r_website_id').append(option);
            }
            $('#r_website_id').attr('disabled',false);
            $('#r_website_id').find('option:first').attr('selected',true);
        });
    });


})(jQuery);
</script>